from machine import Pin
import time

class SU03T:
    def __init__(self, pin_number):
        self.pulse_pin = Pin(pin_number, Pin.IN)  # 初始化引脚
        self.last_rising_time = 0  # 上升沿时间
        self.pulse_active = False   # 标记脉冲信号激活状态
        self.recognition_index = -1  # 用于存储当前的识别序号

        # 设置中断，检测脉冲信号的上升沿和下降沿
        self.pulse_pin.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=self.pulse_callback)

    def pulse_callback(self, pin):
        current_time = time.ticks_ms()  # 获取当前时钟时间（毫秒）

        if self.pulse_pin.value() == 1 and not self.pulse_active:
            # 检测到上升沿
            self.last_rising_time = current_time
            self.pulse_active = True  # 标记脉冲信号为激活状态
        elif self.pulse_pin.value() == 0 and self.pulse_active:
            # 检测到下降沿
            pulse_period = current_time - self.last_rising_time
            self.recognition_index = pulse_period - 1  # 计算语音识别序号
            print("脉冲宽度: {} 毫秒, 语音识别序号: {}".format(pulse_period, self.recognition_index))
            self.pulse_active = False  # 重置脉冲状态

    def get_recognition_index(self):
        return self.recognition_index  # 返回当前的语音识别序号


